import React, { useState, useEffect } from 'react';
import { Button } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import {
  openNotification_util, fetchsync_util,
  resultdata_to_formdata, addkey_for_mxdata,
  convertISODateTimeToYYYYMMDDHHMMSS,
  combile_mxdata_mxcol_util,
  checkdatavalid_util_formdata_mx,
  view_item_util,
} from '../util/util.js'
import Customfielditem_hook from '../newmes/customfielditem_hook.js'
import moment from 'moment'
import 'moment/locale/zh-cn'
import Xm_wlmx_hook from './xm_wlmx_hook.js';
import Gysyb_fjmx_hook from './gysyb_fjmx_hook.js';
import { SaveOutlined } from '@ant-design/icons';
import { use_xm_initformdata_view_xj, use_gysyb_fjmx_column_initformdata, use_xj_wlmx_column_initformdata } from './use_zbzx_config.js';
moment.locale('zh-cn')
var storage = window.localStorage;
import useStore from '../../useStore.js'
import { dropByCacheKey } from 'react-router-cache-route'


const Gysxj_form = () => {
  //动态数据源
  const [dynDatasObject, setdynDatasObject] = useState({

  })
  const [isloading, setisloading] = useState(true)
  const [wlmxdata, setwlmxdata] = useState([])
  const [fjmxdata, setfjmxdata] = useState([])
  const [wlmxcolums, setwlmxcolums] = useState(use_xj_wlmx_column_initformdata)
  const [fjmxcolums, setfjmxcolums] = useState(use_gysyb_fjmx_column_initformdata)
  const [wlmxdelidarr, setwlmxdelidarr] = useState([])
  const [fjmxdelidarr, setfjmxdelidarr] = useState([])

  /**
   * 强制刷新明细表 用于特殊场景
   */
  const [switche, setswitche] = useState(true);
  const forceupdate = () => { setswitche(false) }
  useEffect(() => { switche ? "1" : setswitche(true) }, [switche])

  //主表数据
  const [formdata, setformdata] = useState(use_xm_initformdata_view_xj)
  const { setnowroute, collapsed } = useStore();


  //加载主表数据
  const loadformdata = async (id) => {
    let rtdata = await fetchsync_util("/admin/zbzx/query_gysxj_byid", 'POST', { id }, "json")
    rtdata.resultdata.formdata.create_time = rtdata.resultdata.formdata.create_time ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.create_time) : ""
    rtdata.resultdata.formdata.update_time = rtdata.resultdata.formdata.update_time ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.update_time) : ""
    rtdata.resultdata.formdata.sqsj = rtdata.resultdata.formdata.sqsj ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.sqsj) : ""
    rtdata.resultdata.formdata.fbsj = rtdata.resultdata.formdata.fbsj ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.fbsj) : ""
    rtdata.resultdata.formdata.ybjzsj = rtdata.resultdata.formdata.ybjzsj ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.ybjzsj) : ""
    rtdata.resultdata.formdata.xjjzsj = rtdata.resultdata.formdata.xjjzsj ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.xjjzsj) : ""
    rtdata.resultdata.formdata.kbsj = rtdata.resultdata.formdata.kbsj ? convertISODateTimeToYYYYMMDDHHMMSS(rtdata.resultdata.formdata.kbsj) : ""
    setformdata({ ...formdata, ...resultdata_to_formdata(rtdata.resultdata.formdata, formdata) });
    console.log(rtdata.resultdata, "rtdata.resultdata");
    setwlmxdata(addkey_for_mxdata(rtdata.resultdata.wlmxdata))
    setfjmxdata(addkey_for_mxdata(rtdata.resultdata.fjmxdata))
    console.log(rtdata.resultdata.formdata.xmzt, "rtdata.resultdata.formdata.xmzt");
    if (rtdata.resultdata.formdata.xmzt == '询价结束') {
      setwlmxcolums(view_item_util(use_xj_wlmx_column_initformdata()))
      setfjmxcolums(view_item_util(use_gysyb_fjmx_column_initformdata()))
    }
  }

  // 页面进入加载数据
  useEffect(() => {
    loadformdata(JSON.parse(storage.pre_gysxj_item).data.id)

    setisloading(false)
  }, [])

  useEffect(() => {
    if (formdata.xmzt.value == '询价结束') {
      setwlmxcolums(view_item_util(use_xj_wlmx_column_initformdata()))
      setfjmxcolums(view_item_util(use_gysyb_fjmx_column_initformdata()))
    }
    else {
      console.log(111111111);
      //如果附件明细中存在附件，则报价字段为必填
      if (fjmxdata.some(item => item.gys_fj)) {
        setwlmxcolums([...wlmxcolums.map(item => {
          if (item.dataIndex == "blbj") {
            item.bt = false
          }
          return item
        })])
        setswitche(false)
      }
      else {
        setwlmxcolums([...wlmxcolums.map(item => {
          if (item.dataIndex == "blbj") {
            item.bt = true
          }
          return item
        })])
        setswitche(false)
      }
    }
  }, [fjmxdata, formdata.xmzt.value])


  //设置value
  const setfield = (onekey, value, settype) => {
    if (settype == 'single') {
      var newitem = formdata[onekey]
      newitem.value = value
      let newformdata = Object.assign({}, formdata, { [onekey]: newitem });
      setformdata(newformdata)
    }
    else if (settype == "muti") {
      let [tansferarr, selectrow, newformdata] = [onekey, value, {}];
      tansferarr.forEach(item => {
        var newitem = formdata[item.target]
        newitem.value = selectrow ? selectrow[item.origin] : ""
        newformdata = Object.assign({}, formdata, { [item.target]: newitem });
      })
      setformdata(newformdata)
    }

  }


  const handleupload = async () => {
    var newwlmxdatalist = combile_mxdata_mxcol_util(wlmxdata, wlmxcolums)

    if (!checkdatavalid_util_formdata_mx(newwlmxdatalist)) {
      openNotification_util("物料明细必填校验不通过，无法保存")
      return
    }
    //拼接明细
    let rtdata = await fetchsync_util("/admin/zbzx/gysxj", 'POST', { formdata, fjmxdata, wlmxdata }, "json")
    openNotification_util(rtdata.rtmessage)
    dropByCacheKey('gysxj_list')
    dropByCacheKey('gysxj_form')
    setnowroute({ route: "/shipSRM/zbzx/gysxj_list", title: "供应商询价", closeroute: "/shipSRM/zbzx/gysxj_form" })
  }



  const renderfileditem = () => {
    var formdataarr = []
    for (var formitemkey in formdata) {
      formdata[formitemkey].inputType == "none" ? "" : formdataarr.push(formdata[formitemkey])
    }
    var renderstr = formdataarr.map(item => {
      var rtitem = item.input_type == "space_item" ?
        <Customfielditem_hook form={formdata} item={{ inputType: "none" }}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
        :
        <Customfielditem_hook form={formdata} item={formdata[item.dataIndex]}
          dynDatasObject={dynDatasObject}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
      return rtitem
    }
    )
    return renderstr
  }

  return (

    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "5.9vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem"
    }}
    data-page-type="form">

      <div style={{width:"100%",height:"100%",backgroundColor:"white",overflow:"auto"}}>
      <div style={{
        width: "100%", height: "7%", position: "sticky", top: "1%", backgroundColor: "white", color: "black", display: "flex",
        zIndex: 105, borderBottom: "2px solid #a91f24"
      }}>


        <div style={{ width: "40%", textAlign: "left", paddingRight: "1rem", display: "flex", alignItems: "center", fontWeight: "600" }}>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          工具栏
        </div>

        <div style={{ width: "60%", textAlign: "right", paddingRight: "1rem" }}>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <Button type="primary" onClick={handleupload}
            style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.2rem" }}>
            <SaveOutlined /> 报价 </Button>

        </div>
      </div>

      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap", marginBottom: "2rem"
        }}>
          {renderfileditem()}
        </div>
        {/* 主表区域结束 */}
        {/* 物料明细区域*/}
        <div style={{
          height: "1.2rem", marginLeft: "2%", position: "relative", width: "96%", textIndent: "0.5rem", color: "#666666",
          backgroundColor: "white", lineHeight: "1.2rem", fontSize: "14px", fontWeight: "500", textAlign: "left", borderLeftStyle: "solid",
          borderWidth: "0.3rem", borderColor: "#a91f24", marginTop: "1rem", marginBottom: "0.5rem", letterSpacing: "0.05rem"
        }}>
          物料明细
        </div>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
        }}>
          {isloading ?
            (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>            <LoadingOutlined /></div>)
            :
            <div style={{ position: "relative", width: "100%", overflowX: "auto", marginBottom: "1rem" }}>
              {switche && <Xm_wlmx_hook colmuns={wlmxcolums} datasource={wlmxdata}
                styleobj={{ height: "70%" }}
                dynDatasObject={dynDatasObject}
                formdata={formdata}
                handledelid={ids => { ids.length !== 0 ? setwlmxdelidarr([...wlmxdelidarr, ...ids]) : ''; }}
                handgetmxdata={(tabledata) => {
                  addkey_for_mxdata(tabledata)
                  setwlmxdata(tabledata)
                }}
                ifshowaddbtn={JSON.parse(storage.pre_gysxj_item).type == "edit" || JSON.parse(storage.pre_gysxj_item).type == "add" ? true : false}
                handlechangeFormdata={(data) => {
                  setformdata(data)
                }}
                forceupdate={forceupdate}
              />}</div>
          }
        </div>
        {/* 应标附件明细区域 */}
        <div style={{
          height: "1.2rem", marginLeft: "2%", position: "relative", width: "96%", textIndent: "0.5rem", color: "#666666",
          backgroundColor: "white", lineHeight: "1.2rem", fontSize: "14px", fontWeight: "500", textAlign: "left", borderLeftStyle: "solid",
          borderWidth: "0.3rem", borderColor: "#a91f24", marginTop: "1rem", marginBottom: "0.5rem", letterSpacing: "0.05rem"
        }}>
          附件明细
        </div>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
        }}>
          {isloading ?
            (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>            <LoadingOutlined /></div>)
            :
            <div style={{ position: "relative", width: "100%", overflowX: "auto", marginBottom: "1rem" }}>
              {switche && <Gysyb_fjmx_hook colmuns={fjmxcolums} datasource={fjmxdata}
                styleobj={{ height: "70%" }}
                dynDatasObject={dynDatasObject}
                formdata={formdata}
                handledelid={ids => { ids.length !== 0 ? setfjmxdelidarr([...fjmxdelidarr, ...ids]) : ''; }}
                handgetmxdata={(tabledata) => {
                  addkey_for_mxdata(tabledata)
                  setfjmxdata(tabledata)
                }}
                ifshowaddbtn={JSON.parse(storage.pre_gysxj_item).type == "edit" || JSON.parse(storage.pre_gysxj_item).type == "add" ? true : false}
                handlechangeFormdata={(data) => {
                  setformdata(data)
                }}
                forceupdate={forceupdate}
              />}</div>
          }
        </div>
      </div>
      </div>
    </div>
  )
}


export default Gysxj_form
var styles = {
  kshcontainer: {
    width: "98%", position: "relative", backgroundColor: "white", color: "#666",
    borderRadius: "10px", paddingBottom: "2rem", overflow: "visible"
  },
}